//
//  MyInfoViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/21.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit

class MyInfoViewController: UITableViewController {

    @IBOutlet weak var photoButton: UIButton!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var autnLabel: UILabel!
    @IBOutlet weak var phoneLabel: UILabel!
    
    var user: User.UserInfo?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        fetchUserInfo()
    }
    
    @IBAction func approveInfo(_ sender: UITapGestureRecognizer) {
        if let info = user {
            if info.cert_flag == 2 {
                performSegue(withIdentifier: "finsishAuthSence", sender: nil)
            } else {
                switch info.cert_step {
                case 0: performSegue(withIdentifier: "IDCardViewController", sender: nil)
                case 1:performSegue(withIdentifier: "DrivingLicenseViewController", sender: nil)
                case 2:break
                case 3:performSegue(withIdentifier: "RejectViewController", sender: nil)
                case 4:performSegue(withIdentifier: "finsishAuthSence", sender: nil)
                default:break
                }
            }
        }
    }
    
    func makeAccoundInfo() {
        
        if let info = user {
            
            let photo = User.isLogin() ? "default_user_photo" : "default_user-1"
            let image = UIImage(named: photo)
            
            self.photoButton.setBackgroundImage(image, for: .normal)
            
            nameLabel.text = info.user_name == "" ? "" : info.user_name
            nameLabel.textColor = UIColor(red: 10.00 / 255.00, green: 11.00 / 255.00, blue: 65.00 / 255.00, alpha: 1.0)
            
            phoneLabel.text = info.telephone
            phoneLabel.textColor = UIColor(red: 10.00 / 255.00, green: 11.00 / 255.00, blue: 65.00 / 255.00, alpha: 1.0)
            if info.cert_flag == 2 {
                autnLabel.text = "已认证"
            } else {
                switch info.cert_step {
                case 0,1:autnLabel.text = "未认证"
                case 2:  autnLabel.text = "审核中"
                case 3:  autnLabel.text = "已驳回"
                case 4:  autnLabel.text = "已认证通过"
                default:break
                }
            }            
            //更新本地用户信息
            if let user = User.info() {
                user.certStep = info.cert_step
                User.saveUserInfo(user)
                
                self.slipViewController?.menuViewController?.refresh()
            }

            if info.cert_flag == 1 {
                autnLabel.textColor = UIColor(red: 245.00 / 255.00, green: 108.00 / 255.00, blue: 61.00 / 255.00, alpha: 1.0)
            } else {
                autnLabel.textColor = UIColor(red: 10.00 / 255.00, green: 11.00 / 255.00, blue: 65.00 / 255.00, alpha: 1.0)
            }
            
            if info.avatar_path != "" {
                let offerUrl = URL(string: kImageServerName + info.avatar_path)
                if offerUrl != nil {
                    photoButton.setBackgroundImageWith(offerUrl, for: .normal, placeholder: image)
                }
            }
        }
    }
    
    @objc func fetchUserInfo() {
        
        JZLoading.showLoadingWith(toView: self.view)
        User.fetchUserInfo(success: { [weak self] data in
            self?.tableView.isHidden = false
            JZLoading.hideLoading()
            self?.user = data
            self?.makeAccoundInfo()
        }) { [weak self] message in
            JZLoading.hideLoading()
            self?.showError(message)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func chooseHeaderImage(_ sender: Any) {
        
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.allowsEditing = true
        
        let actionSheet = UIAlertController(title: nil,
                                            message: "请你选择头像",
                                            preferredStyle: .actionSheet)
        
        let actionPhoto = UIAlertAction(title: "相册选择", style: .default) { [weak self] info in
            photoPicker.sourceType = .photoLibrary
            //在需要的地方present出来
            self?.present(photoPicker, animated: true, completion: nil)
        }
        
        let actionCamera = UIAlertAction(title: "拍照", style: .default) { [weak self] info in
            photoPicker.sourceType = .camera
            //在需要的地方present出来
            self?.present(photoPicker, animated: true, completion: nil)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        actionSheet.addAction(actionPhoto)
        actionSheet.addAction(actionCamera)
        actionSheet.addAction(cancelAction)
        
        present(actionSheet, animated: true, completion: nil)
    }
}

extension MyInfoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //获得照片
        let image:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
        
        User.uploadFile(image) { [weak self] imagePath in
            User.updateuserInfo(photoAdress: imagePath, success: { info in
                
                XHProgressHUD.showSuccess("设置成功")
                self?.photoButton.setBackgroundImage(image, for: .normal)
                Pay.changeUserphoto(photoAddress: imagePath)
                self?.slipViewController?.menuViewController?.refresh()
                
            }, failure: { error in
                XHProgressHUD.showError("设置失败")
            })
            self?.dismiss(animated: true, completion: nil)
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "finsishAuthSence" {
            let controller = segue.destination as? AudiFinishViewController
            controller?.userName = user?.user_name
            controller?.identityCard = user?.identify_card
        }
    }
}



